<template>
  <div>
    <div class="header">
      <div class="page-header">
        <el-page-header @back="goBack" content="菜单管理">
        </el-page-header>
      </div>

      <el-button type="success" icon="el-icon-plus" @click="addData" size="small"
                 style="margin-top:10px;margin-left: 20px">新增菜单
      </el-button>
      <div class="search">
        <el-input v-model="pageRequest.key" style="width: 200px;margin-right: 10px" placeholder="按菜单名称查找"
                  size="small"></el-input>
        <el-button type="primary" icon="el-icon-search" size="small" @click="getMenuPageList">搜索</el-button>
      </div>
    </div>
    <el-card class="box-card"
             shadow="always">
      <template>
        <el-table
            :data="menuList"
            :header-cell-style="{color:'#333',fontFamily:'MicrosoftYaHeiUI',fontSize:'14px',fontWeight:900}"
            style="width: 100%;margin-bottom: 20px;"
            row-key="menuId"
            size="small"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

          <el-table-column
              prop="label"
              width="150"
              :show-overflow-tooltip='true'
              label="菜单名称">
          </el-table-column>

          <el-table-column
              :show-overflow-tooltip='true'
              width="120"
              prop="menuType"
              label="菜单类型">
            <template slot-scope="scope">
              <el-tag size="medium"
                      :type="scope.row.menuType === 0 ? 'warning' : scope.row.menuType === 1?'success':'info'">
                {{ scope.row.menuType === 0 ? '目录' : scope.row.menuType === 1 ? '组件' : '按钮' }}
              </el-tag>
            </template>
          </el-table-column>


          <el-table-column
              :show-overflow-tooltip='true'
              width="120"
              prop="path"
              label="路由路径">
          </el-table-column>

          <el-table-column
              prop="routeName"
              :show-overflow-tooltip='true'
              label="路由名称">
          </el-table-column>

          <el-table-column
              :show-overflow-tooltip='true'
              width="120"
              prop="component"
              label="组件路径">
          </el-table-column>

          <el-table-column
              :show-overflow-tooltip='true'
              prop="visible"
              label="显示状态">
            <template slot-scope="scope">
              <el-switch
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="0"
                  inactive-value="1"
                  @change="handleSwitchChange(scope.row)"
                  v-model="scope.row.visible">
              </el-switch>
            </template>
          </el-table-column>


          <el-table-column
              :show-overflow-tooltip='true'
              prop="status"
              label="菜单状态">
            <template slot-scope="scope">
              <el-switch
                  size="small"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="0"
                  inactive-value="1"
                  @change="handleSwitchChange(scope.row)"
                  v-model="scope.row.status">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column
              :show-overflow-tooltip='true'
              width="150"
              prop="permissions"
              label="权限标识">
          </el-table-column>
          <el-table-column
              :show-overflow-tooltip='true'
              prop="icon"
              label="图标">
          </el-table-column>
          <el-table-column
              :show-overflow-tooltip='true'
              prop="createBy"
              label="创建人">
          </el-table-column>
          <el-table-column
              width="150"
              :show-overflow-tooltip='true'
              prop="createTime"
              label="创建时间">
          </el-table-column>
          <el-table-column
              :show-overflow-tooltip='true'
              prop="updateBy"
              label="更新人">
          </el-table-column>
          <el-table-column
              width="150"
              :show-overflow-tooltip='true'
              prop="updateTime"
              label="更新时间 ">
          </el-table-column>

          <!--                    <el-table-column prop="delFlag" width="100" label="删除标志"></el-table-column>-->
          <el-table-column
              fixed="right"
              label="操作"
              width="120">
            <template slot-scope="scope">
              <el-button @click="updateData(scope.row)" icon="el-icon-edit" type="text" size="mini">修改
              </el-button>
              <el-button @click="deleteData(scope.row.menuId)" icon="el-icon-delete" type="text"
                         size="small">删除
              </el-button>
            </template>

          </el-table-column>
        </el-table>
      </template>

      <div class="block">
        <el-pagination
            style="float: right"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageRequest.pageNum"
            :page-sizes="[ 10, 15, 20]"
            :page-size="pageRequest.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageResult.total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
        width="810px"
        top="3vh"
        @close="closeDialog"
        :title="operate.title"
        :visible.sync="dialogFormVisible">
      <el-form :model="form" :inline="true" :rules="menuRules" ref="form" style="padding: 0px 50px" size="small">

        <el-form-item label="菜单类型" v-if="operate.opType === 0" :label-width="formLabelWidth" prop="menuType">
          <el-select v-model="form.menuType" @change="selectMenuType()" placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级菜单" :label-width="formLabelWidth" prop="parentId">
          <el-cascader
              size="small"
              placeholder="请选择"
              :props="cascaderConfig"
              v-model="form.parentId"
              key="menuId"
              :options="parentMenuList">
          </el-cascader>
        </el-form-item>

        <el-form-item label="菜单名称" :label-width="formLabelWidth" prop="label">
          <el-input
              v-model="form.label"
              autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="路由路径" v-if="form.menuType === 1" :label-width="formLabelWidth" prop="path">
          <el-input
              v-model="form.path"
              autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="路由名" v-if="form.menuType === 1" :label-width="formLabelWidth" prop="routeName">
          <el-input
              v-model="form.routeName"
              autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="组件" v-if="form.menuType === 1" :label-width="formLabelWidth" prop="component">
          <el-input
              v-model="form.component"
              autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="显示状态" :label-width="formLabelWidth">
          <el-switch
              v-model="form.visible"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用"
              inactive-text="禁用"
              active-value="0"
              inactive-value="1">
          </el-switch>
        </el-form-item>


        <el-form-item label="菜单状态" :label-width="formLabelWidth">
          <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用"
              inactive-text="禁用"
              active-value="0"
              inactive-value="1">
          </el-switch>
        </el-form-item>

        <el-form-item label="权限标识" :label-width="formLabelWidth" prop="permissions">
          <el-input
              v-model="form.permissions"
              autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input-number v-model="form.orderBy" :min="0" :max="10"
                           label="描述文字"></el-input-number>
        </el-form-item>


        <el-form-item label="icon" v-if="form.menuType !== 2" :label-width="formLabelWidth" prop="icon">
          <el-input
              v-model="form.icon"
              autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入内容"
              v-model="form.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" size="medium">取 消</el-button>
        <el-button type="primary" @click="operate.opType === 0?addMenu('form'):updateMenu()" size="medium">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {addMenu, deleteMenu, getDirMenuList,getComponentMenuList, getMenuPageList, updateMenu} from "../../api/menu";
import {mapActions} from "vuex";
import DeepCopyUtil from "@/utils/DeepCopyUtil";

export default {
  name: 'MenuManage.vue',
  components: {},
  data() {
    return {
      menuIdList: [],
      menuList: [],
      parentMenuList: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        key: ''
      },
      pageResult: {
        total: 0,
        totalPage: 0,
        size: 0,
      },
      dialogFormVisible: false,
      formLabelWidth: '120px',
      operate: {
        opType: 0,
        title: ''
      },
      form: {},
      options: [{
        value: 0,
        label: '目录'
      }, {
        value: 1,
        label: '组件'
      }, {
        value: 2,
        label: '按钮'
      }],
      cascaderConfig: {
        label: 'label',
        value: 'menuId',
        checkStrictly: true
      },
      menuRules: {
        menuType: [
          {required: true, message: '菜单类型不能为空', trigger: 'change'}
        ],
        parentId: [
          {required: true, message: '上级菜单不能为空', trigger: 'change'}
        ],
        label: [
          {required: true, message: '菜单名称不能为空', trigger: 'blur'}
        ],
        permissions: [
          {required: true, message: '权限标识不能为空', trigger: 'blur'}
        ],
        path: [
          {required: true, message: '路由路径不能为空', trigger: 'blur'}
        ],
        routeName: [
          {required: true, message: '路由名称不能为空', trigger: 'blur'}
        ],
        component: [
          {required: true, message: '组件不能为空', trigger: 'blur'}
        ],
      },
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //方法集合
  methods: {
    ...mapActions('menu', ['refreshMenu']),
    updateData(menu) {
      this.form = DeepCopyUtil.copy(menu)
      this.operate.opType = 1;
      this.operate.title = '编辑菜单'
      this.dialogFormVisible = true;
      if (this.form.menuType === 2) {
        this.getMenuComponentList()
      }
    },
    addData() {
      this.operate.opType = 0;
      this.operate.title = '新增菜单'
      this.dialogFormVisible = true;
      this.form = {orderBy: 0, status: '0', visible: '0'};

    },
    deleteData(menuId) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteMenu(menuId);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getMenuPageList() {
      getMenuPageList(this.pageRequest).then(res => {
        if (res.code === 200) {
          this.menuList = res.data.dataList;
          this.pageResult.size = res.data.size
          this.pageResult.total = res.data.total
          this.pageResult.totalPage = res.data.totalPage
          if (res.data.size === 0 && res.data.pageNum > 1) {
            this.pageRequest.pageNum--;
            this.getMenuPageList();
          }
        } else {
          this.$message({
            type: 'error',
            message: '菜单加载失败'
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '菜单加载失败'
        });
      })
    },
    updateMenu() {
      this.form.parentId = this.form.parentId[this.form.parentId.length - 1]
      updateMenu(this.form).then(res => {
        if (res.code === 200) {
          this.refreshAll()
          this.$message({
            type: 'success',
            message: '修改成功'
          });
        } else {
          this.$message({
            type: 'error',
            message: '修改失败，' + res.message
          });
        }
        this.dialogFormVisible = false;
      }).catch(err => {
        this.dialogFormVisible = false;
        this.$message({
          type: 'error',
          message: '修改失败'
        });
      })
    },
    addMenu(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.parentId = this.form.parentId[this.form.parentId.length - 1]
          addMenu(this.form).then(res => {
            if (res.code === 200) {
              this.refreshAll()
              this.$message({
                type: 'success',
                message: '新增成功'
              });
            } else {
              this.$message({
                type: 'error',
                message: '新增失败，' + res.message
              });
            }
            this.dialogFormVisible = false;
          }).catch(err => {
            this.dialogFormVisible = false;
            this.$message({
              type: 'error',
              message: '新增失败'
            });
          })
        } else {
          return false;
        }
      });
    },
    deleteMenu(menuId) {
      deleteMenu({menuId}).then(res => {
        if (res.code === 200) {
          this.refreshAll();
          this.$message({
            type: 'success',
            message: '删除成功'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.message
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '删除失败'
        });
      })
    },
    getMenuDirList() {
      getDirMenuList().then(res => {
        if (res.code === 200) {
          this.parentMenuList = res.data
        }
      }).catch(err => {

      })
    },
    selectMenuType() {
      // 取消校验状态和提示信息
      this.$refs.form.clearValidate();
      if (this.form.menuType === 0 || this.form.menuType === 1) {
        this.cascaderConfig.checkStrictly = true
        this.getMenuDirList();
      } else {
        this.cascaderConfig.checkStrictly = false
        this.getMenuComponentList()
      }
    },
    refreshAll() {
      this.getMenuPageList();
      this.refreshMenu();
      this.getMenuDirList()
    },

    getMenuComponentList() {
      getComponentMenuList().then(res => {
        if (res.code === 200) {
          this.parentMenuList = res.data
        }
      }).catch(err => {

      })
    },
    handleSwitchChange(row) {
      updateMenu(row).then(res => {
        if (res.code === 200) {
          this.refreshAll()
          this.$message({
            type: 'success',
            message: '修改成功'
          });
        } else {
          this.$message({
            type: 'error',
            message: '修改失败，' + res.message
          });
        }
        this.dialogFormVisible = false;
      }).catch(err => {
        this.dialogFormVisible = false;
        this.$message({
          type: 'error',
          message: '修改失败'
        });
      })
    },
    cancel() {
      this.dialogFormVisible = false;
      this.getMenuPageList();
    },
    handleSizeChange(pageSize) {
      console.log(`每页 ${pageSize} 条`);
      this.pageRequest.pageSize = pageSize;
      this.getMenuPageList()
    },
    handleCurrentChange(pageNum) {
      console.log(`当前页: ${pageNum}`);
      this.pageRequest.pageNum = pageNum;
      this.getMenuPageList()
    },
    goBack() {
      window.history.back()
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    closeDialog() {
      // 取消校验状态和提示信息
      this.$refs.form.clearValidate();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.refreshAll()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  },
  beforeCreate() {
  },//生命周期 - 创建之前
  beforeMount() {
  }, //生命周期 - 挂载之前
  beforeUpdate() {
  }, //生命周期 - 更新之前
  updated() {
  }, //生命周期 - 更新之后
  beforeDestroy() {
  }, //生命周期 - 销毁之前
  destroyed() {
  }, //生命周期 - 销毁完成
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style scoped>

.header {
  /*display: flex;*/
  /*!*垂直对齐*!*/
  /*align-items: center;*/
  height: 50px;
  background-color: #eff4f9;
}

.page-header {
  float: left;
  margin-top: 15px
}

.search {
  float: right;
  margin-top: 10px
}

.box-card {
  height: 100%;
  padding-bottom: 5px;
}

.block {
  margin-top: 5px;

}

.el-form-item .el-textarea {
  width: 205px
}

.el-form-item .el-select {
  width: 205px
}

.el-form-item .el-cascader {
  width: 205px
}

.el-form-item .el-input {
  width: 205px
}

.el-form-item {
  width: 325px;
}


</style>
